import 'dart:convert';

import 'package:ecy_app_flutter/ecycommon/EcyCommonWidgets.dart';
import 'package:ecy_app_flutter/routes/goods/model/EcyGoodsHomeCategoryListModel.dart';
import 'package:ecy_app_flutter/routes/goods/model/EcyGoodsHomeCategoryModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../../constant/color_constant.dart';
import '../../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../../model/EcyApiCommonResponse.dart';
import '../../model/EcyGoodsSkuListModel.dart';
import '../EcyGoodsCategoryListView.dart';
import '../EcyGoodsSkuListView.dart';

class EcyGoodsCateogrySelectPage extends EcyCommonBaseWidget {
  final EcyGoodsHomeCategoryModel selectedModel;
  EcyGoodsCateogrySelectPage(this.selectedModel, this.onSelectNewValue);
  final ValueChanged<EcyGoodsHomeCategoryModel> onSelectNewValue;
  @override
  _EcyGoodsCateogrySelectPageState createState() {
    return _EcyGoodsCateogrySelectPageState(
        this.selectedModel, this, this.onSelectNewValue);
  }
}

class _EcyGoodsCateogrySelectPageState extends EcyCommonBaseWidgetState {
  int currentIndex = 0;
  bool requesting = false;

  late EcyGoodsHomeCategoryModel selectedModel;
  late EcyGoodsHomeCategoryListModel categoryListModel =
      EcyGoodsHomeCategoryListModel(0, 0, 0, []);
  late EcyGoodsCategoryListView categoryListView;

  EcyGoodsSkuListModel skuListModel = EcyGoodsSkuListModel(0, 0, 0, 0, []);
  late EcyGoodsSkuListView skuListView;

  final EcyCommonBaseWidget controller;
  final ValueChanged<EcyGoodsHomeCategoryModel> onSelectNewValue;

  _EcyGoodsCateogrySelectPageState(
      this.selectedModel, this.controller, this.onSelectNewValue);

  @override
  void initState() {
    super.initState();

    categoryListView =
        EcyGoodsCategoryListView(categoryListModel, 0, (newValue) {
      this.selectedModel = newValue;
      this.categoryListView.reloadIndexData(newValue.index ?? 0);
      requestSkuListData(1);
    });
    skuListView = EcyGoodsSkuListView(skuListModel, 0, (page) {
      requestSkuListData(page);
    });
    requestData();
  }

  void requestSkuListData(int page) async {
    super.requestData();
    controller.showLoading();
    var response = await Future.wait([
      EcyRequestbasemanager().post("/app/api/app/commoditySku/list", {
        "size": "10",
        "current": page,
        "name":
            this.selectedModel.name == "全部" ? "" : this.selectedModel.name ?? ""
      }),
    ]);
    controller.dismissLoading();
    if (response != null) {
      var _skuResp = response[0];
      if (_skuResp != null) {
        reloadSKUArea(_skuResp, page);
      }
    }
  }

  void reloadSKUArea(_skuResp, page) {
    var _skuRespModel =
        EcyApiCommonResponse.fromJson(_skuResp, (_skuResp) => json);
    if (_skuRespModel.code == 0) {
      EcyGoodsSkuListModel _skuListModel =
          EcyGoodsSkuListModel.fromJson(_skuResp["data"]);
      if (page <= 1) {
        skuListModel = _skuListModel;
      } else {
        skuListModel.records.addAll(_skuListModel.records);
      }
      skuListView.reloadData(skuListModel, page);
    }
  }

  void requestCategoryListData() async {
    super.requestData();
    controller.showLoading();
    var response = await Future.wait([
      EcyRequestbasemanager().post(
          "/app/api/app/commodityCategory/list", {"size": "10", "current": 1, "name": ""}),
    ]);
    controller.dismissLoading();
    if (response != null) {
      var _resp = response[0];
      if (_resp != null) {
        reloadCategoryArea(_resp);
      }
    }
  }

  void reloadCategoryArea(_categoryResp) {
    var _cateogryRespModel =
        EcyApiCommonResponse.fromJson(_categoryResp, (_categoryResp) => json);
    if (_cateogryRespModel.code == 0) {
      EcyGoodsHomeCategoryListModel _labelListModel =
          EcyGoodsHomeCategoryListModel.fromJson(_categoryResp["data"]);
      var all = EcyGoodsHomeCategoryModel(
          "全部", "全部", "-1", "assets/images/ic_home_allip.png", true, 0, "-1");
      _labelListModel.records.insert(0, all);
      categoryListView.reloadData(_labelListModel);
    }
  }

  @override
  void requestData() {
    super.requestData();
    requestCategoryListData();
    requestSkuListData(1);
  }

  Future<void> _onRefresh() async {
    requestData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xFFFFFFFF),
        appBar: AppBar(
          backgroundColor: ColorConstant.White,
          title: Text(
            selectedModel.name ?? "",
            style: TextStyle(
                fontSize: 16.sp,
                color: Color(0xD9000000),
                fontWeight: FontWeight.w700),
          ),
        ),
        body: Stack(alignment: Alignment.topCenter, children: [
          Container(
              color: Color(0xFFFFFFFF),
              margin: EdgeInsets.only(left: 0.w, right: 0.w, top: 0.h),
              width: MediaQuery.of(context).size.width - 0.w,
              height: 32.h,
              child: SizedBox.fromSize(
                size: Size(MediaQuery.of(context).size.width - 0.w, 32.h),
                child: categoryListView,
              )),
          Container(
            color: Color(0xFFF5F5F5),
            margin: EdgeInsets.only(top: 40.h, bottom: 0.h),
            child: RefreshIndicator(
              onRefresh: _onRefresh,
              child: skuListView,
            ),
          )
        ]));
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    super.dispose();
  }
}
